<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<spring:eval expression="@propertyConfigurer.getProperty('url.cdn')" var="cdnUrl" />
<spring:eval expression="@propertyConfigurer.getProperty('build.version')" var="version" />
<!DOCTYPE html>
<html lang="${language}">
<head>
    <meta charset="UTF-8">
    <title><spring:message code="voj.teacher.new-class.title" text="New Class" /> | ${websiteName}</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="${description}">
    <meta name="author" content="Haozhe Xie">
    <!-- Icon -->
    <link href="${cdnUrl}/img/favicon.ico?v=${version}" rel="shortcut icon" type="image/x-icon">
    <!-- StyleSheets -->
    <link rel="stylesheet" type="text/css" href="${cdnUrl}/css/bootstrap.min.css?v=${version}" />
    <link rel="stylesheet" type="text/css" href="${cdnUrl}/css/bootstrap-responsive.min.css?v=${version}" />
    <link rel="stylesheet" type="text/css" href="${cdnUrl}/css/flat-ui.min.css?v=${version}" />
    <link rel="stylesheet" type="text/css" href="${cdnUrl}/css/font-awesome.min.css?v=${version}" />
    <link rel="stylesheet" type="text/css" href="${cdnUrl}/css/teacher/style.css?v=${version}" />
    <link rel="stylesheet" type="text/css" href="${cdnUrl}/css/teacher/new-user.css?v=${version}" />
    <!-- JavaScript -->
    <script type="text/javascript" src="${cdnUrl}/js/jquery-1.11.1.min.js?v=${version}"></script>
    <script type="text/javascript" src="${cdnUrl}/js/bootstrap.min.js?v=${version}"></script>
    <script type="text/javascript" src="${cdnUrl}/js/flat-ui.min.js?v=${version}"></script>
    <script type="text/javascript" src="${cdnUrl}/js/md5.min.js?v=${version}"></script>
    <script type="text/javascript" src="${cdnUrl}/js/pace.min.js?v=${version}"></script>
    <script type="text/javascript" src="${cdnUrl}/js/xlsx.core.min.js?v=${version}"></script>
    <style>
        .fileupload #preview {
            font-size: 11px;
        }
        .fileupload #preview table{
            border: 1px solid #d2dfe0
        }
        .fileupload #preview td{
            border: 1px solid #d2dfe0
        }
        .fileupload .setting {
            display: none;
            position: absolute;
            right: -200px;
            font-family: 'Courier New', Courier, monospace;
            font-size: 12px;
            padding: 10px;
            background-color: #d2dfe06e;
            border-radius: 10px;
        }
        .fileupload .setting label{
            margin: 5px;
        }
        .fileupload .setting input{
            width: 70px !important;
            height: 15px;
            border: 1px solid #d2dfe0;
            border-radius: 3px;
            margin: 0 5px;
        }
        .fileupload .setting input[type=button]{
            line-height: 20px;
            height: auto;
            width: auto;
            font-size: 14.99px;
            font-weight: bolder;
            background-color: #1abc9c;
            color: white;
            cursor: pointer;
            padding: 10px 12px 9px 12px;
            border-radius: 6px;
        }
        .fileupload {
            margin-top: 60px;
            position: relative;
            min-height: 100px;
        }
    </style>
    <!--[if lte IE 9]>
        <script type="text/javascript" src="${cdnUrl}/js/jquery.placeholder.min.js?v=${version}"></script>
    <![endif]-->
    <!--[if lte IE 7]>
        <script type="text/javascript"> 
            window.location.href='<c:url value="/not-supported" />';
        </script>
    <![endif]-->
</head>
<body>
    <div id="wrapper">
        <!-- Sidebar -->
        <%@ include file="/WEB-INF/views/teacher/include/sidebar.jsp" %>
        <div id="container">
            <!-- Header -->
            <%@ include file="/WEB-INF/views/teacher/include/header.jsp" %>
            <!-- Content -->
            <div id="content">
                <h2 class="page-header"><i class="fa fa-user"></i> <spring:message code="voj.teacher.new-class.new-class" text="New Class" /></h2>
                <form id="profile-form" onSubmit="return false;" enctype="multipart/form-data">
                    <div class="alert alert-error hide"></div> <!-- .alert-error -->
                    <div class="alert alert-warn hide"></div> <!-- .alert-error -->
                    <div class="alert alert-success hide"><spring:message code="voj.teacher.new-class.class-created" text="The class has been created successfully." /></div> <!-- .alert-success -->
                    <div class="control-group row-fluid">
                        <label for="username"><spring:message code="voj.teacher.new-class.uploadfile" text="Upload File" /></label>
                        <button type="button" class="span12" style="margin: 0;height: 40px;border-radius: 6px;border: 1px solid #bdc3c7;background-color: #eee;" onclick="triggerUploadFile(event)"><spring:message  code="voj.teacher.new-class.uploadfile" text="Upload File" /></button>
                        <input id="file" class="span12" style="display: none;" type="file" onchange="readWorkbookFromLocalFile(event)"/>
                        <div class="fileupload">
                            <div class="setting">
                                <select onchange="changeModel(event.target.value)">
                                    <c:forEach var="classModel" items="${classModels}" varStatus="status">
                                        <option value="${status.index}">${classModel.name}</option>
                                    </c:forEach>
                                </select>
                                <label for="class_model_term"><spring:message  code="voj.teacher.new-class.term" text="Term" /></label>
                                <input type="text" name="class_model_term" onchange="model['class_model_term']=event.target.value;">
                                <label for="class_model_lessonId"><spring:message  code="voj.teacher.new-class.lesson-id" text="Lesson Id" /></label>
                                <input type="text" name="class_model_lessonId" onchange="model['class_model_lessonId']=event.target.value;">
                                <label for="class_model_lessonNum"><spring:message  code="voj.teacher.new-class.lesson-num" text="Lesson Num" /></label>
                                <input type="text" name="class_model_lessonNum" onchange="model['class_model_lessonNum']=event.target.value;">
                                <label for="class_model_lessonName"><spring:message  code="voj.teacher.new-class.lesson-name" text="Lesson Name" /></label>
                                <input type="text" name="class_model_lessonName" onchange="model['class_model_lessonName']=event.target.value;">
                                <label for="class_model_teacher"><spring:message  code="voj.teacher.new-class.teacher" text="Teacher" /></label>
                                <input type="text" name="class_model_teacher" onchange="model['class_model_teacher']=event.target.value;">
                                <label for="class_model_studentsCode"><spring:message  code="voj.teacher.new-class.student-code" text="Student Code" /></label>
                                <input class="long" type="text" name="class_model_studentsCode" onchange="model['class_model_studentsCode']=event.target.value;">
                                <label for="class_model_studentsName"><spring:message  code="voj.teacher.new-class.student-name" text="Student Name" /></label>
                                <input class="long" type="text" name="class_model_studentsName" onchange="model['class_model_studentsName']=event.target.value;">
                                <label for="class_model_studentsName"><spring:message  code="voj.teacher.new-class.student-class" text="Student Class" /></label>
                                <input class="long" type="text" name="class_model_studentsClass" onchange="model['class_model_studentsClass']=event.target.value;">
                                <br>
                                <br>
                                <input type="button" value='<spring:message  code="voj.common.mark" text="Make" />' onclick="mark()">
                            </div>
                            <div id="preview">

                            </div>
                        </div>
                    </div> <!-- .control-group -->
                    <div class="control-group row-fluid">
                        <label for="prefer-language"><spring:message code="voj.common.prefer-language" text="Prefer Language" /></label>
                        <select id="prefer-language" name="preferLanguage">
                        <c:forEach var="language" items="${languages}">
                            <option value="${language.languageSlug}">${language.languageName}</option>
                        </c:forEach>
                        </select>
                    </div> <!-- .control-group -->
                    <div class="row-fluid">
                        <div class="span12">
                            <button class="btn btn-primary" type="submit" onclick="onSubmit()"><spring:message code="voj.teacher.new-class.create-class" text="Create Class" /></button>
                        </div> <!-- .span12 -->
                    </div> <!-- .row-fluid -->
                </form> <!-- #profile-form -->
            </div> <!-- #content -->    
        </div> <!-- #container -->
    </div> <!-- #wrapper -->
    <!-- Java Script -->
    <!-- Placed at the end of the document so the pages load faster -->
    <%@ include file="/WEB-INF/views/teacher/include/footer-script.jsp" %>
    <script>
        var workbook;
        var defaultSheet;
        function readWorkbookFromLocalFile(e) {
            $('.alert-error', '#profile-form').addClass('hide');
            document.querySelector("#preview").innerHTML = "";
            document.querySelector(".setting").style.display = "none";
            var file = e.target.files[0];
            if(file){
                var reader = new FileReader();
                reader.onload = function(e) {
                    var data = e.target.result;
                    try {
                        workbook = XLSX.read(data, {type: 'binary'});
                        let sheets = Object.keys(workbook.Sheets);
                        defaultSheet = Object.keys(workbook.Sheets)[0];
                        if(sheets.length >= 2) {
                            defaultSheet = prompt('<spring:message code="voj.teacher.new-class.multi-sheets" text="Multiple Sheets." />', defaultSheet);
                        }
                        document.querySelector("#preview").innerHTML = XLSX.utils.sheet_to_html(workbook.Sheets[defaultSheet]);
                        document.querySelector(".setting").style.display = "block";
                    } catch (error) {
                        $('.alert-error', '#profile-form').html('<spring:message code="voj.teacher.new-class.file-match-fail" text="File Match Fail." />「'+file.type+'」.');
                        $('.alert-error', '#profile-form').removeClass('hide');
                    }
                };
                reader.readAsBinaryString(file);
            } else {
                $('.alert-error', '#profile-form').html('<spring:message code="voj.teacher.new-class.file-upload-fail" text="File Upload Fail." />');
                $('.alert-error', '#profile-form').removeClass('hide');
            }
        }
        function str2cnt(str) {
            if(str=="$") return 36;
            let length = str.length-1;
            let base = 1;
            let res = 0;
            for(let i=length;i>=0;i--){
                res += base * (str.charCodeAt(i)-64);
                base *= 26;
            }
            return res-1;
        }
        function cnt2str(cnt) {
            let res = "";
            cnt += 1;
            while(cnt>0){
                cnt--;
                res = String.fromCharCode(cnt%26+65) + res;
                cnt = Math.floor(cnt/26);
            }
            return res;
        }
        function markitem(item, table) {
            table.querySelector(`#sjs-\${model[item]}`).style.backgroundColor = modelColor[item];
        }
        function markitems(item, table) {
            let s = model[item].replace(']','').replace('[','').split('-')[0];
            let e = model[item].replace(']','').replace('[','').split('-')[1];
            let a = str2cnt(s.match(/[A-Z]+/)[0]);
            let b = parseInt(s.match(/\d+/)[0]);
            let c = str2cnt(e.match(/[A-Z]+|\$/)[0]);
            let d = parseInt(e.match(/\d+|\$/)[0]);
            for(let i=a;i<=c||c==-1;i++){
                for(let j=b;j<=d||isNaN(d);j++){
                    try {
                        table.querySelector(`#sjs-\${cnt2str(i)+j}`).style.backgroundColor = modelColor[item];
                    } catch (error) {
                        break;
                    }
                }
            }
        }
        function getitem(item) {
            return workbook.Sheets[defaultSheet][model[item]].v;
        }
        function getitems(item) {
            let res = [];
            let s = model[item].replace(']','').replace('[','').split('-')[0];
            let e = model[item].replace(']','').replace('[','').split('-')[1];
            let a = str2cnt(s.match(/[A-Z]+/)[0]);
            let b = parseInt(s.match(/\d+/)[0]);
            let c = str2cnt(e.match(/[A-Z]+|\$/)[0]);
            let d = parseInt(e.match(/\d+|\$/)[0]);
            for(let i=a;i<=c||c==-1;i++){
                for(let j=b;j<=d||isNaN(d);j++){
                    try {
                        res.push(workbook.Sheets[defaultSheet][cnt2str(i)+j].v);
                    } catch (error) {
                        break;
                    }
                }
            }
            return res;
        }
        function clear(table) {
            table.querySelectorAll("tr").forEach(item=>{
                item.querySelectorAll("td").forEach(item=>item.style.backgroundColor = "white");
            });
        }
        function mark() {
            let table = document.querySelector("#preview table");
            if(table){
                clear(table);
                markitem("class_model_term", table);
                markitem("class_model_lessonId", table);
                markitem("class_model_lessonNum", table);
                markitem("class_model_lessonName", table);
                markitem("class_model_teacher", table);
                markitems("class_model_studentsCode", table);
                markitems("class_model_studentsName", table);
                markitems("class_model_studentsClass", table);
            }
        }
        function getPostData(){
            try {
                workbook.Sheets[defaultSheet];
            } catch (error) {
                $('.alert-error', '#profile-form').html('Err 1000: <spring:message code="voj.teacher.new-class.error-process" text="Error Process." />');
                $('.alert-error', '#profile-form').removeClass('hide');
                throw new Error("1000")
            }
            let res = {};
            res["term"] = getitem("class_model_term");
            res["lessonId"] = getitem("class_model_lessonId");
            res["lessonNum"] = getitem("class_model_lessonNum");
            res["lessonName"] = getitem("class_model_lessonName");
            res["teacher"] = getitem("class_model_teacher");
            res["studentsCode"] = getitems("class_model_studentsCode");
            res["studentsName"] = getitems("class_model_studentsName");
            res["studentsClass"] = getitems("class_model_studentsClass");
            return res;
        }
        function changeModel(op){
            model = models[op];
        }
        var models = [
            <c:forEach var="classModel" items="${classModels}">
            {
                "class_model_term":"${classModel.term}",
                "class_model_lessonId":"${classModel.lessonId}",
                "class_model_lessonNum":"${classModel.lessonNum}",
                "class_model_lessonName":"${classModel.lessonName}",
                "class_model_teacher":"${classModel.teacherName}",
                "class_model_studentsCode":"${classModel.studentsCode}",
                "class_model_studentsName":"${classModel.studentsName}",
                "class_model_studentsClass":"${classModel.studentsClass}"
            },
            </c:forEach>
        ]
        var model = models[0];
        var modelColor = {
            "class_model_term":"#86E3CE",
            "class_model_lessonId":"#D0E6A5",
            "class_model_lessonNum":"#FFDD94",
            "class_model_lessonName":"#FA897B",
            "class_model_teacher":"#CCABD8",
            "class_model_studentsCode":"#ABB6C8",
            "class_model_studentsName":"#DADADA",
            "class_model_studentsClass":"#C2C4B6"
        }
        for(let key in model) {
            document.getElementsByName(key)[0].value = model[key];
            document.getElementsByName(key)[0].style.backgroundColor = modelColor[key];
        }
    </script>
    <script>
        function triggerUploadFile(e) {
            document.getElementById('file').addEventListener("change",(event)=>{
                e.target.innerHTML = event.target.files[0].name;
            })
            $('#file').click();
        }
    </script>
    <script type="text/javascript">
        function onSubmit() {
            // var formData = new FormData();
            $('.alert-success', '#profile-form').addClass('hide');
            $('.alert-warn', '#profile-form').addClass('hide');
            $('.alert-error', '#profile-form').addClass('hide');
            let data = getPostData();
            $('button[type=submit]', '#profile-form').attr('disabled', 'disabled');
            $('button[type=submit]', '#profile-form').html('<spring:message code="voj.common.please-wait" text="Please wait..." />');
            /* var fileUpload = new File([document.getElementById('file').files[0]], encodeURI(document.getElementById('file').files[0].name), {
                type: document.getElementById('file').type
            }); */
            data.languageSlug = $('#prefer-language').val();
            // formData.append("file", fileUpload);
            return doCreateClassAction(data);
        }
    </script>
    <script type="text/javascript">
        function doCreateClassAction(postData) {
            $.ajax({
                type: 'POST',
                url: '<c:url value="/teacher/newClass.action" />',
                data: postData,
                dataType: 'JSON',
                traditional: true,
                success: function(result){
                    return processCreateClassResult(result);
                }
            });
        }
    </script>
    <script type="text/javascript">
        function processCreateClassResult(result) {
            // console.log(result);
            if ( result['isSuccessful'] ) {
                $('input').val('');
                $('.alert-success', '#profile-form').removeClass('hide');
            } else {
                let errorMessage  = '';
                let warnMessage = '';
                if ( result['isParamEmpty'] ) {
                    errorMessage += '<spring:message code="voj.teacher.new-class.param-empty" text="Parameters are missing. Please check if the document you submitted contains all parameters of semester, course number, course name and teacher." /><br>';
                }
                if ( result['isLanguageIllegal'] ) {
                    errorMessage += '<spring:message code="voj.common.language-empty" text="You can&apos;t leave Language Preference empty." /><br>';
                }
                if ( result['isStudentDataIllega'] ) {
                    errorMessage += '<spring:message code="voj.teacher.new-class.student-data-illega" text="Illegal student data. Please make sure every student has name, student number and class." /><br>';
                }
                if ( result['isStudentEmpty'] ) {
                    warnMessage += '<spring:message code="voj.teacher.new-class.student-empty" text="You are allowed to create a class without students, but you must understand that an empty class is meaningless." /><br>';
                }
                $('.alert-warn', '#profile-form').html(warnMessage);
                $('.alert-warn', '#profile-form').removeClass('hide');
                $('.alert-error', '#profile-form').html(errorMessage);
                $('.alert-error', '#profile-form').removeClass('hide');
            }
            $('button[type=submit]', '#profile-form').removeAttr('disabled');
            $('button[type=submit]', '#profile-form').html('<spring:message code="voj.teacher.new-class.create-class" text="Create Class" />');
        }
    </script>
</body>
<%@ include file="/WEB-INF/views/include/script.jsp" %>
</html>